import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:live_music/controller/video_list_controller.dart';
// import 'package:get/get.dart';
// import 'package:live_music/controller/video_list_controller.dart';
import 'package:live_music/event/videoListEvent.dart';
import 'package:live_music/models/moment_detail_model.dart';
import 'package:live_music/pages/video/widget/disk_widget.dart';
import 'package:live_music/pages/video/widget/video_bottom_bar_widget.dart';
import 'package:live_music/pages/video/widget/video_comment_widget.dart';
import 'package:live_music/pages/video/widget/video_right_bar_widget.dart';
import 'package:live_music/pages/video/widget/video_share_widget.dart';
import 'package:live_music/services/operationServiece.dart';
import 'package:live_music/utils/cgq_utils.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/toast_utils.dart';
import 'package:video_player/video_player.dart';
import 'widget/like_gesture_widget.dart';

///视频播放列表组件

class SingleVideoIndexPage extends StatefulWidget {
  SingleVideoIndexPage({Key key, this.videoItem, this.index}) : super(key: key);
  MomentDetailModel videoItem;
  int index;
  @override
  _SingleVideoIndexPageState createState() => _SingleVideoIndexPageState();
}

class _SingleVideoIndexPageState extends State<SingleVideoIndexPage> {
  VideoPlayerController _videoPlayerController;
  bool _playing = false;
  MomentDetailModel _videoItem;
  bool showDuration = false;
  @override
  void initState() {
    super.initState();
    setState(() {
      _videoItem = widget.videoItem;
    });
    _videoPlayerController = VideoPlayerController.network(
        _videoItem.video.sourceUrl != "" && !kIsWeb
            ? _videoItem.video.sourceUrl
            : _videoItem.video.url)
      ..initialize().then((_) {
        // 确保在初始化视频后显示第一帧，直至在按下播放按钮。
        setState(() {});
      });
    _videoPlayerController.addListener(() {
      setState(() {
        _playing = _videoPlayerController.value.isPlaying;
      });
    });
    _videoPlayerController.setLooping(true);
    _playOrPause();
    EventBusUtils.getInstance().fire(CurVideoListIndexEvent(widget.index));
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    return Scaffold(
        backgroundColor: Colors.black,
        body: Container(
          color: Color(0XFF000000),
          child: Center(
              child: GestureDetector(
                  child: Container(
                      width: double.infinity,
                      height: double.infinity,
                      color: Color(0XFF000000),
                      child: Stack(
                        children: [
                          LikeGestureWidget(
                            onSingleTap: () {
                              _playOrPause();
                            },
                            child: _getVideoPlayer(),
                          ),
                          Positioned(
                              right: 10,
                              bottom: 110,
                              child: VideoRightBarWidget(
                                onAddFavorite: (isLike) {
                                  addFavorite(isLike);
                                },
                                onCollect: (isLike) {
                                  onCollect(isLike);
                                },
                                onClickComment: () {
                                  showBottomComment();
                                },
                                videoItem: _videoItem,
                                onClickShare: () {
                                  showBottomShare();
                                },
                                onClickHeader: () {
                                  // widget.onClickHeader?.call();
                                },
                              )),
                          Positioned(
                              right: 2,
                              bottom: 20,
                              child: VinylDisk(videoItem: _videoItem)),
                          Positioned(
                            left: 12,
                            bottom: 20,
                            child: VideoBottomBarWidget(videoItem: _videoItem),
                          ),
                          showDuration || !_playing
                              ? Positioned(
                                  left: 0,
                                  bottom: 50,
                                  right: 0,
                                  child: Container(
                                      padding: const EdgeInsets.only(
                                          right: 10, left: 10),
                                      height: 20,
                                      child: new Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            Text(
                                              (_videoPlayerController
                                                      .value.position
                                                      .toString()
                                                      .split('.')[0]
                                                      .split(':')[1] +
                                                  ":" +
                                                  _videoPlayerController
                                                      .value.position
                                                      .toString()
                                                      .split('.')[0]
                                                      .split(':')[2]),
                                              style: TextStyle(
                                                  fontSize: 14,
                                                  color: Color(0xffefefef)),
                                            ),
                                            Text(
                                              " / ",
                                              style: TextStyle(
                                                  fontSize: 14,
                                                  color: Color(0xffefefef)),
                                            ),
                                            Text(
                                              (_videoPlayerController
                                                      .value.duration
                                                      .toString()
                                                      .split('.')[0]
                                                      .split(':')[1] +
                                                  ":" +
                                                  _videoPlayerController
                                                      .value.duration
                                                      .toString()
                                                      .split('.')[0]
                                                      .split(':')[2]),
                                              style: TextStyle(
                                                  fontSize: 14,
                                                  color: Color(0xffefefef)),
                                            ),
                                          ])))
                              : Container(),
                          Positioned(
                            bottom: 0,
                            left: 0,
                            right: 0,
                            child: Container(
                              padding:
                                  const EdgeInsets.only(right: 10, left: 10),
                              color: Color.fromRGBO(0, 0, 0, 0.5),
                              height: 20,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  //进度条
                                  Expanded(
                                    child: SliderTheme(
                                        data: SliderThemeData(
                                          trackHeight:
                                              showDuration || !_playing ? 3 : 1,
                                          activeTrackColor:
                                              showDuration || !_playing
                                                  ? Colors.white
                                                  : Colors.grey[700], // 激活的轨道颜色
                                          inactiveTrackColor:
                                              showDuration || !_playing
                                                  ? Colors.grey
                                                  : Colors.grey[850],
                                          thumbColor: showDuration || !_playing
                                              ? Colors.white
                                              : Colors.grey[800], // 滑块颜色
                                          thumbShape: RoundSliderThumbShape(
                                              //  滑块形状，可以自定义
                                              enabledThumbRadius:
                                                  showDuration || !_playing
                                                      ? 5
                                                      : 1 // 滑块大小
                                              ),
                                        ),
                                        child: Slider(
                                          // inactiveColor: Colors.grey,
                                          // activeColor: Color(0xffFFFFFF),
                                          max: _videoPlayerController
                                              .value.duration.inMilliseconds
                                              .truncateToDouble(),
                                          value: _videoPlayerController
                                              .value.position.inMilliseconds
                                              .truncateToDouble(),
                                          onChangeStart: (newRating) {
                                            setState(() {
                                              showDuration = true;
                                            });
                                          },
                                          onChangeEnd: (newRating) {
                                            setState(() {
                                              showDuration = false;
                                            });
                                          },
                                          onChanged: (newRating) {
                                            _videoPlayerController.seekTo(
                                                Duration(
                                                    milliseconds:
                                                        newRating.truncate()));
                                          },
                                        )),
                                    flex: 1,
                                  ),

                                  //倍速下拉菜单
                                  // DropdownButtonHideUnderline(
                                  //   child: DropdownButton2(
                                  //     hint: Text(
                                  //       _selectedValue,
                                  //       style: TextStyle(
                                  //         fontSize: 18,
                                  //         color: Color(0xffefefef),
                                  //       ),
                                  //     ),
                                  //     items: items
                                  //         .map((item) => DropdownMenuItem<String>(
                                  //               value: item,
                                  //               child: Text(
                                  //                 '${item}x',
                                  //                 style: const TextStyle(
                                  //                   fontSize: 16,
                                  //                 ),
                                  //               ),
                                  //             ))
                                  //         .toList(),
                                  //     // value: _selectedValue,
                                  //     icon: Visibility(
                                  //         visible: false,
                                  //         child: Icon(Icons.arrow_downward)),
                                  //     onChanged: (value) async {
                                  //       double val = double.parse(value as String);
                                  //       setState(() {
                                  //         if (val == 1.0) {
                                  //           _selectedValue = '倍速';
                                  //         } else {
                                  //           _selectedValue = '${value as String}x';
                                  //         }
                                  //       });
                                  //     },
                                  //     dropdownWidth: 100,
                                  //     buttonWidth: 60,
                                  //     iconSize: 36,
                                  //     iconEnabledColor: Colors.white,
                                  //     buttonPadding:
                                  //         const EdgeInsets.only(left: 10),
                                  //   ),
                                  // ),
                                ],
                              ),
                            ),
                          )
                        ],
                      )))),
        ));
  }

  onCollect(bool isLiked) async {
    _videoItem.video.hasCollected = isLiked;
    if (isLiked) {
      _videoItem.video.collectCount++;
    } else {
      _videoItem.video.collectCount--;
    }
    Map<String, dynamic> data = {
      "targetId": _videoItem.video.id,
      "targetType": 'VIDEO',
    };
    if (isLiked) {
      await OperationServiece.collect(data);
    } else {
      await OperationServiece.cancelCollect(data);
    }

    setState(() {
      _videoItem = _videoItem;
    });
  }

  addFavorite(bool isLiked) async {
    _videoItem.hasLiked = isLiked;
    if (isLiked) {
      _videoItem.likeCount++;
    } else {
      _videoItem.likeCount--;
    }
    Map<String, dynamic> data = {
      "targetId": _videoItem.id,
      "targetType": 'MOMENT',
    };
    if (isLiked) {
      await OperationServiece.like(data);
    } else {
      await OperationServiece.cancelLike(data);
    }

    setState(() {
      _videoItem = _videoItem;
    });
  }

  void _playOrPause() {
    _playing = !_playing;
    if (_playing) {
      _videoPlayerController.play();
    } else {
      _videoPlayerController.pause();
    }
    setState(() {});
  }

  _getVideoPlayer() {
    return Stack(
      children: [
        _videoPlayerController.value.isInitialized
            ? Container(
                width: double.infinity,
                height: double.infinity,
                alignment: Alignment.center,
                child: AspectRatio(
                  aspectRatio: _videoPlayerController.value.aspectRatio,
                  child: VideoPlayer(_videoPlayerController),
                ),
              )
            : Center(
                // child: Container(
                //   child: Text("视频加载中"),
                // ),
                  child: Container(
                  width: double.infinity,
                  child: CgqUtils.imageCache(
                   _videoItem.video.url+ "?x-oss-process=video/snapshot,t_0,f_jpg,w_0,h_0,m_fast,ar_auto",
                    fit: BoxFit.fitWidth,
                  ),
                )
              ),
        kIsWeb
            ? InkWell(
                onTap: _playOrPause,
                child: Center(
                  child: Container(),
                ))
            : Container(),
        _playing == true ? Container() : _getPauseButton(),
      ],
    );
  }

  _getPauseButton() {
    return Center(
        child: Container(
            width: 100,
            height: 100,
            child: Image.asset(
              'assets/images/common/pause.webp',
              fit: BoxFit.fill,
            )));
  }

  //展示评论
  void showBottomComment() {
    //EasyLoading.showToast('评论列表待开发');
    showModalBottomSheet(
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        builder: (context) {
          return Container(
              //  margin: EdgeInsets.only(bottom:MediaQuery.of(context).viewInsets.bottom),
              constraints: BoxConstraints(
                  minHeight: 150, //设置最小高度（必要）
                  maxHeight: MediaQuery.of(context).size.height / 5 * 3),
              child: VideoCommentWidget(momentDetailData: _videoItem));
        });
  }

  //展示分享布局
  void showBottomShare() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true, //可滚动 解除showModalBottomSheet最大显示屏幕一半的限制
        shape: RoundedRectangleBorder(
          borderRadius: const BorderRadius.only(
            topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
          ),
        ),
        backgroundColor: Colors.white,
        builder: (context) {
          return VideoShareWidget(momentDetailData: _videoItem);
        });
  }
}
